﻿/*
 * Copyright (c) 2010, Sergey Loktin (mailto://shadowconsp@gmail.com)
 * Licensed under The MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;

namespace MoonyWeather
{
    /// <summary>
    /// Interaction logic for WeatherSettings.xaml
    /// </summary>
    public partial class WeatherSettings : UserControl
    {
        MoonyWeatherCtrl _weatherCtrl = null;
        string oldWOEID = string.Empty;
        int oldCursorPos = 0;

        public WeatherSettings(MoonyWeatherCtrl DesktopElement)
        {
            InitializeComponent();
            _weatherCtrl = DesktopElement;
            this.DataContext = _weatherCtrl;
            rbC.IsChecked = _weatherCtrl.UnitIsC;
            rbF.IsChecked = !_weatherCtrl.UnitIsC;
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            for (int i = 0; i < (e.Source as TextBox).Text.Length; i++)
            {
                if (!char.IsDigit((e.Source as TextBox).Text[i]))
                {
                    (e.Source as TextBox).Text = oldWOEID;
                    (e.Source as TextBox).SelectionStart = oldCursorPos;
                    return;
                }
            }

            oldWOEID = (e.Source as TextBox).Text;
            _weatherCtrl.WOEID = oldWOEID;
        }
        
        private void TextBox_SelectionChanged(object sender, RoutedEventArgs e)
        {
            oldCursorPos = (e.Source as TextBox).SelectionStart;
        }

        private void RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            _weatherCtrl.UnitIsC = false;
        }

        private void RadioButton_Unchecked(object sender, RoutedEventArgs e)
        {
            _weatherCtrl.UnitIsC = true;
        }

        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            Properties.Settings.Default.woeid = _weatherCtrl.WOEID;
            Properties.Settings.Default.unit = _weatherCtrl.UnitIsC;
            Properties.Settings.Default.Save();
        }

        private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
            e.Handled = true;
        }
    }
}
